package tester.cobertura;

import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

import net.sourceforge.cobertura.instrument.CoberturaFile;

/**
 * Because Cobertura (our reporting tool) is typically used via command
 * line ant commands, we needed to come up with a "hack" to couple our 
 * tester with Cobertura.  This class, Instrumentor, serves that purpose.
 * The instrumentor will go and look for all classes which are annotated 
 * with the "@Instrument" tag, and then instrument that class' byte code.
 * @author Weston Jossey
 * @version 1.0
 * @since December 12 2008
 * 
 *
 */
public class Instrumentor {
	private static final Logger logger = Logger
	.getLogger(Instrumentor.class);
	
	AnnotationScanner scanner;
	Set<CoberturaFile> files;
	Set<String> classes;

	public Instrumentor() {
		scanner = new AnnotationScanner(tester.cobertura.Instrument.class);
	}

	public synchronized void instrumentClasses() {
		try {
			classes = scanner.scan();

			if (classes != null) {	
				files = new HashSet<CoberturaFile>(classes.size());
				for (String val : classes) {
					val = val.replace('.', '/') + ".class";
					files.add(new CoberturaFile("bin/", val));
				}

				new net.sourceforge.cobertura.instrument.Main()
						.explicitCall(".", "cobertura.ser", "bin/", null,
								null, new String[] { ".*" }, null, files
										.toArray(new CoberturaFile[0]));

			}

		} catch (Exception e) {
			logger.error("Scanner threw exception: "
					+ e.getLocalizedMessage());
			//System.err.println("Scanner threw exception: "
			//		+ e.getMessage());
			e.printStackTrace();
		}
	}

	/*
	 * Generates the HTML reports to the directory "reports" and uses the source
	 * code found at the directories passed in the ellipsis. I left basedir null
	 * because the way Cobertura's code is structured, if I have a value for
	 * basedir, then it will evealuate all passed arguments in the ellipsis as
	 * files.
	 */
	public void generateReports() {
		try {
			// new net.sourceforge.cobertura.reporting.Main()
			// .explicitArgumets(null, "cobertura.ser", "reports",
			// "html", "/Users/w_jossey/NUTester/src");
			new net.sourceforge.cobertura.reporting.Main()
					.explicitArgumets(null, "cobertura.ser", "reports/",
							"html", "src/");

		} catch (Exception e) {
			logger.error(e.getLocalizedMessage());
			e.printStackTrace();
		}

	}

}
